package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerMaintainComponent;
import com.chcit.mobile.di.module.MaintainModule;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.contract.MaintainContract;
import com.chcit.mobile.mvp.model.entity.BpartnerBean;
import com.chcit.mobile.mvp.model.entity.MaintainBean;
import com.chcit.mobile.mvp.model.entity.Statu;
import com.chcit.mobile.mvp.presenter.MaintainPresenter;
import com.chcit.mobile.mvp.ui.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.ui.adapter.MaintainAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;


import static com.jess.arms.utils.Preconditions.checkNotNull;


public class MaintainFragment extends ScanFragment<MaintainPresenter> implements MaintainContract.View {

    @BindView(R.id.et_maintain_productName)
    SuperEditText etProductName;
    @BindView(R.id.bt_maintain_query)
    Button btQuery;
    @BindView(R.id.pr_maintain_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_maintain_list)
    RecyclerView mRecyclerView;
    MaintainAdapter mAdapter;
    MaintainBean mMaintainBean;
    List<MaintainBean> mMaintainBeans;

    private ArrayList<BpartnerBean> bpartners;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private BpartnerBean bpartnerBean;
    private Statu mStatu;
    private String headers[] = {"选择货主", "选择日期", "养护级别"};
    private int REQUEST_CODE = this.getClass().hashCode();

    public static MaintainFragment newInstance() {
        MaintainFragment fragment = new MaintainFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMaintainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .maintainModule(new MaintainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_maintain, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle("养护记录查询");
        mCommonToolbar.addRightText(2, "", null);
        mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
            pop();
            l.setOnClickListener(null);
            if (getActivity() != null) {
                _mActivity.finish();
            }

        });
        initDropDownMenu();
        initRecyclerView();
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(mContext);
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean("", "不限"));

        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(mContext, bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            if (position == 0) {
                bpartnerBean = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });

        //日期选择
        final View constellationView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateFrom = constellationView.findViewById(R.id.pop_date_from);
        tvDateTo = constellationView.findViewById(R.id.pop_date_drive);

        tvDateFrom.getCenterTextView().setText(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(1));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 6));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        TextView ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tvDateFrom.getCenterString()+"\\n"+ tvDateTo.getCenterString();
                mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
            }
        });

        //存货状态
        final ListView dateView = new ListView(getContext());

        final List<Statu> status = new ArrayList<>();
        status.add(new Statu("", "不限"));
        final GirdDropDownAdapter<Statu> dateAdapter = new GirdDropDownAdapter<Statu>(getContext(), status);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            mStatu = status.get(position);
            if (position == 0) {
                mStatu = null;
            }
            mDropDownMenu.setTabText(position == 0 ? headers[2] : status.get(position).getName());
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l->{
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l->{
            tvDateFrom.setCenterString("");
        });
        mPresenter.getBpartners(bpartnerBeans -> {
            bpartners.addAll(bpartnerBeans);
            bpartnerAdapter.notifyDataSetChanged();
        });


        mPresenter.getLevels(status1 -> {
            status.addAll(status1);
            dateAdapter.notifyDataSetChanged();
        });

    }

    private void initRecyclerView() {
        mAdapter = new MaintainAdapter(mMaintainBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                mMaintainBean = (MaintainBean) adapter.getData().get(position);
               startForResult(MaintainDetailFragment.newInstance(mMaintainBean), REQUEST_CODE);
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
            }
        });
        mRecyclerView.setAdapter(mAdapter);

    }


    @OnClick(R.id.bt_maintain_query)
    public void onViewClicked() {
        mAdapter.getData().clear();
         /*  start:0
    limit:25
    orgID:1000063
    checkResult:1
    productName:545454
    showLot:true
    conserveLevel:0
    dateFrom:2018-11-01T00:00:00
    dateTo:2018-11-10T00:00:00
    processed:N
    appSessionID:1541745126336.12*/
        JSONObject data = new JSONObject();
        data.put("start", 0);
        data.put("limit", 25);
        data.put("showLot", true);
        data.put("processed","N");
        if (!etProductName.getText().toString().isEmpty()) {
            data.put("productName", etProductName.getText().toString());
        }
        if (!tvDateFrom.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateFrom", tvDateFrom.getCenterTextView().getText().toString());
        }
        if (!tvDateTo.getCenterTextView().getText().toString().isEmpty()) {
            data.put("dateTo", tvDateTo.getCenterTextView().getText().toString());
        }
        if (mStatu != null) {
            data.put("conserveLevel", mStatu.getId());
        }
        if (bpartnerBean != null) {
            data.put("orgID", bpartnerBean.getId());
        }
        mPresenter.getData(data, list -> {

            mAdapter.addData(list);
        });
    }


    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {

    }
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
        }
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            mCommonToolbar.setTitle("养护记录查询");
            mCommonToolbar.getViewByTag(1).setOnClickListener(l -> {
                pop();
                l.setOnClickListener(null);
                if (getActivity() != null) {
                    _mActivity.finish();
                }
            });
        }
        super.onHiddenChanged(hidden);

    }
}
